package com.ethereal.petmanagement.filter;

import com.ethereal.petmanagement.entity.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

// 拦截所有.do请求，但排除登录、注册等接口
@WebFilter("*.do")
public class LoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        String uri = req.getRequestURI();

        // 不需要登录验证的接口
        if (uri.contains("login.do") || uri.contains("register.do")) {
            chain.doFilter(req, resp);
            return;
        }

        HttpSession session = req.getSession(false);
        User loginUser = session == null ? null : (User) session.getAttribute("loginUser");

        if (loginUser == null) {
            // 未登录，跳转到提示页面
            resp.sendRedirect("login.jsp");
        } else {
            chain.doFilter(req, resp); // 已登录，放行
        }
    }

    @Override
    public void destroy() {

    }
}
